'''
Created on 14/03/2011
@summary: Dbus utils
@author: chukysoria
'''

DBUS_PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"
import dbus

# DBus helpers
class DBusObject(object):
    """
    @summary: Wrapper for a dbus object, so that the bus name and object name only needs
    to be specified once.
    """

    def __init__(self, bus_name, object_name):
        bus = dbus.SessionBus()
        self._bus = bus
        self._obj = bus.get_object(bus_name, object_name)

    def __getattr__(self, name):
        def f(*args, **kwargs):
            return getattr(self._obj, name)(*args, **kwargs)
        return f

class DBusInterface(dbus.Interface):
    """
    @summary: Wrapper for a dbus interface, so that the bus name, object name and interface 
    only needs to be specified once.
    """
    def __init__(self, bus_name, object_name, dbus_interface):
        """
        @summary: Construct a proxy for the given interface on the given object.
        @param bus_name: The bus name (string)
        @param object_name: The object name (string)
        @param dbus_interface: An interface the object implements (string)
        """
        self._obj = DBusObject(bus_name, object_name)
        self._dbus_interface = dbus_interface
        self._dbus_props = dbus.Interface(self._obj,DBUS_PROPERTIES_INTERFACE)
        
    def get(self, property_name):
        '''
        @summary: Get the value of a property of the interface
        @param property_name: The name of the property (string)
        @return: The value of the given property (variant)
        '''
        return self._dbus_props.Get(self._dbus_interface, property_name)

    def set(self, property_name, value):
        '''
        @summary: Set the value of a property of the interface
        @param property_name: The name of the property (string)
        @param value: The value to set 
        @todo: Convert to the appropiate Dbus type based on the property
        '''
        self._dbus_props.Set(self._dbus_interface, property_name, value)
        
